package com.core.dto;

import lombok.Data;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.*;

/**
 * @author : HUANG
 * @create : 2025/6/1 20:30
 * @function :
 */
@Data
public class UserDetailsDto implements UserDetails {
    private UserInfoDto user;

    public List<SimpleGrantedAuthority> authorityList;

    public UserDetailsDto() {
    }

    public UserDetailsDto(UserInfoDto users) {
        this.user = users;
        if (users != null) {
            setAuthorities(user.getRolesPermissions());
        }
    }

    public void setAuthorities(String[] roles) {
        List<SimpleGrantedAuthority> authorities = new ArrayList<>();
        if (roles == null) {
            return;
        }
        for (String role : roles) {
            SimpleGrantedAuthority temp = new SimpleGrantedAuthority(role);
            authorities.add(temp);
        }
        this.authorityList = authorities;
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        if (authorityList == null) {
            if (this.user != null) {
                setAuthorities(user.getRolesPermissions());
            }
        }
        return this.authorityList;
    }

    @Override
    public String getPassword() {
        if (user == null) {
            return null;
        }
        return user.getPassword();
    }

    @Override
    public String getUsername() {
        if (user == null) {
            return null;
        }
        return user.getUsername();
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }
}
